/** Map with String keys and Object values. */ privatefinal Map<String, Object> attributes = new LinkedHashMap<>();
@Nullable private Object source;
/** * Constant for the default scope name: {@code ""}, equivalent to singleton * status unless overridden from a parent bean definition (if applicable). * 默认bean作用域 */ publicstaticfinal String SCOPE_DEFAULT = "";
/** * Constant that indicates no external autowiring at all. * 自动注入模式 * @see #setAutowireMode */ publicstaticfinalint AUTOWIRE_NO = AutowireCapableBeanFactory.AUTOWIRE_NO;
/** * Constant that indicates autowiring bean properties by name. * 自动注入通过bean名字 * @see #setAutowireMode */ publicstaticfinalint AUTOWIRE_BY_NAME = AutowireCapableBeanFactory.AUTOWIRE_BY_NAME;
/** * Constant that indicates autowiring bean properties by type. * 自动注入通过bean类型 * @see #setAutowireMode */ publicstaticfinalint AUTOWIRE_BY_TYPE = AutowireCapableBeanFactory.AUTOWIRE_BY_TYPE;
/** * Constant that indicates autowiring a constructor. * 自动注入通过构造函数 * @see #setAutowireMode */ publicstaticfinalint AUTOWIRE_CONSTRUCTOR = AutowireCapableBeanFactory.AUTOWIRE_CONSTRUCTOR;
/** * Constant that indicates determining an appropriate autowire strategy * through introspection of the bean class. * @see #setAutowireMode * @deprecated as of Spring 3.0: If you are using mixed autowiring strategies, * use annotation-based autowiring for clearer demarcation of autowiring needs. */ @Deprecated publicstaticfinalint AUTOWIRE_AUTODETECT = AutowireCapableBeanFactory.AUTOWIRE_AUTODETECT;
/** * Constant that indicates no dependency check at all. * @see #setDependencyCheck */ publicstaticfinalint DEPENDENCY_CHECK_NONE = 0;
/** * Constant that indicates dependency checking for object references. * @see #setDependencyCheck */ publicstaticfinalint DEPENDENCY_CHECK_OBJECTS = 1;
/** * Constant that indicates dependency checking for all properties * (object references as well as "simple" properties). * @see #setDependencyCheck */ publicstaticfinalint DEPENDENCY_CHECK_ALL = 3;
/** * Constant that indicates the container should attempt to infer the * {@link #setDestroyMethodName destroy method name} for a bean as opposed to * explicit specification of a method name. The value {@value} is specifically * designed to include characters otherwise illegal in a method name, ensuring * no possibility of collisions with legitimately named methods having the same * name. * <p>Currently, the method names detected during destroy method inference * are "close" and "shutdown", if present on the specific bean class. */ publicstaticfinal String INFER_METHOD = "(inferred)";
/** Determines if the definition needs to be re-merged. */ volatileboolean stale;
boolean allowCaching = true;
boolean isFactoryMethodUnique = false;
@Nullable volatile ResolvableType targetType;
/** Package-visible field for caching the determined Class of a given bean definition. */ @Nullable volatile Class<?> resolvedTargetType;
/** Package-visible field for caching if the bean is a factory bean. */ @Nullable volatile Boolean isFactoryBean;
/** Package-visible field for caching the return type of a generically typed factory method. */ @Nullable volatile ResolvableType factoryMethodReturnType;
/** Package-visible field for caching a unique factory method candidate for introspection. */ @Nullable volatile Method factoryMethodToIntrospect;
/** Common lock for the four constructor fields below. */ final Object constructorArgumentLock = new Object();
/** Package-visible field for caching the resolved constructor or factory method. */ @Nullable Executable resolvedConstructorOrFactoryMethod;
/** Package-visible field that marks the constructor arguments as resolved. */ boolean constructorArgumentsResolved = false;
/** Package-visible field for caching fully resolved constructor arguments. */ @Nullable Object[] resolvedConstructorArguments;
/** Package-visible field for caching partly prepared constructor arguments. */ @Nullable Object[] preparedConstructorArguments;
/** Common lock for the two post-processing fields below. */ final Object postProcessingLock = new Object();
/** Package-visible field that indicates MergedBeanDefinitionPostProcessor having been applied. */ boolean postProcessed = false;
/** Package-visible field that indicates a before-instantiation post-processor having kicked in. */ @Nullable volatile Boolean beforeInstantiationResolved;
Spring IoC容器对bean定义的加载是从refresh()方法开始的,这个方法是一个模板方法,它的作用是:在创建IoC容器前,如果已经有容器则把容器销毁关闭,然后再重新创建一个新的容器,然后再对容器做初始化。FileSystemXmlApplicationContext通过调用父类的AbstractApplicationContext.refresh()方法实现容器的创建,加载,初始等一系列操作。回到这个类的构造方法,可以看到在构造方法内部调用了refresh()方法。
publicvoidrefresh()throws BeansException, IllegalStateException { synchronized (this.startupShutdownMonitor) { // Prepare this context for refreshing. // 准备此上下文以进行刷新。 prepareRefresh();
// Tell the subclass to refresh the internal bean factory. // 获取beanFactory实例 ConfigurableListableBeanFactory beanFactory = obtainFreshBeanFactory();
// Prepare the bean factory for use in this context. // 准备上下文使用的BeanFactory prepareBeanFactory(beanFactory);
try { // Allows post-processing of the bean factory in context subclasses. // 允许子类处理BeanFactory后置处理器 postProcessBeanFactory(beanFactory);
// Invoke factory processors registered as beans in the context. // 转到ConfigurationClassPostProcessor里面执行 // 执行bean工厂的后置处理器,里面会有非常多的,非常复杂的BeanFactoryPostProcessor实现类的执行。 invokeBeanFactoryPostProcessors(beanFactory);
// Destroy already created singletons to avoid dangling resources. destroyBeans();
// Reset 'active' flag. cancelRefresh(ex);
// Propagate exception to caller. throw ex; }
finally { // Reset common introspection caches in Spring's core, since we // might not ever need metadata for singleton beans anymore... resetCommonCaches(); } } }
/** * Loads the bean definitions via an XmlBeanDefinitionReader. * 通过XmlBeanDefinitionReader加载所有的bean定义, * 此方法在AbstractApplicationContext中定义了抽象,由子类实现。 * * @see org.springframework.beans.factory.xml.XmlBeanDefinitionReader * @see #initBeanDefinitionReader * @see #loadBeanDefinitions */ @Override protectedvoidloadBeanDefinitions(DefaultListableBeanFactory beanFactory)throws BeansException, IOException { // Create a new XmlBeanDefinitionReader for the given BeanFactory. // 创建bean定义读取器,通过回调设置到容器中,不同的子类设置不同的读取器(有些是读取xml配置,有的是读取java代码的bean定义) XmlBeanDefinitionReader beanDefinitionReader = new XmlBeanDefinitionReader(beanFactory);
// Configure the bean definition reader with this context's // resource loading environment. // 加载上下文的环境配置,配置bean定义 beanDefinitionReader.setEnvironment(this.getEnvironment()); // 设置资源加载器, // 因为本类的最上层父类DefaultResourceLoader也继承了DefaultResourceLoader,所以可以直接传this。 beanDefinitionReader.setResourceLoader(this); beanDefinitionReader.setEntityResolver(new ResourceEntityResolver(this));
// Allow a subclass to provide custom initialization of the reader, // then proceed with actually loading the bean definitions. // 允许子类提供自定义的初始化读取器reader,然后处理加载bean定义 initBeanDefinitionReader(beanDefinitionReader); // 加载bean定义 loadBeanDefinitions(beanDefinitionReader); }
// 设置工厂的属性 if (validationMode != XmlValidationModeDetector.VALIDATION_NONE) { factory.setValidating(true); if (validationMode == XmlValidationModeDetector.VALIDATION_XSD) { // Enforce namespace aware for XSD... factory.setNamespaceAware(true); try { factory.setAttribute(SCHEMA_LANGUAGE_ATTRIBUTE, XSD_SCHEMA_LANGUAGE); } catch (IllegalArgumentException ex) { ParserConfigurationException pcex = new ParserConfigurationException( "Unable to validate using XSD: Your JAXP provider [" + factory + "] does not support XML Schema. Are you running on Java 1.4 with Apache Crimson? " + "Upgrade to Apache Xerces (or Java 1.5) for full XSD support."); pcex.initCause(ex); throw pcex; } } }
/** * Parse the elements at the root level in the document: * "import", "alias", "bean". * 解析最顶层的元素,比如bean,import,alias标签 * @param root the DOM root element of the document */ protectedvoidparseBeanDefinitions(Element root, BeanDefinitionParserDelegate delegate){ if (delegate.isDefaultNamespace(root)) { NodeList nl = root.getChildNodes(); for (int i = 0; i < nl.getLength(); i++) { Node node = nl.item(i); if (node instanceof Element) { Element ele = (Element) node; if (delegate.isDefaultNamespace(ele)) { // 处理普通的子元素,比如<bean>、<alise> parseDefaultElement(ele, delegate); } else { // 处理一些功能性配置,比如:<context:component-scan /> // <aop:aspectj-autoproxy /> delegate.parseCustomElement(ele); } } } } else { delegate.parseCustomElement(root); } }
// 进一步解析bean的其他所有属性并统一封装至GenericBeanDefinition类型实例中 AbstractBeanDefinition beanDefinition = parseBeanDefinitionElement(ele, beanName, containingBean); if (beanDefinition != null) { if (!StringUtils.hasText(beanName)) { try { if (containingBean != null) { beanName = BeanDefinitionReaderUtils.generateBeanName( beanDefinition, this.readerContext.getRegistry(), true); } else { beanName = this.readerContext.generateBeanName(beanDefinition); // Register an alias for the plain bean class name, if still possible, // if the generator returned the class name plus a suffix. // This is expected for Spring 1.2/2.0 backwards compatibility. String beanClassName = beanDefinition.getBeanClassName(); if (beanClassName != null && beanName.startsWith(beanClassName) && beanName.length() > beanClassName.length() && !this.readerContext.getRegistry().isBeanNameInUse(beanClassName)) { aliases.add(beanClassName); } } if (logger.isTraceEnabled()) { logger.trace("Neither XML 'id' nor 'name' specified - " + "using generated bean name [" + beanName + "]"); } } catch (Exception ex) { error(ex.getMessage(), ele); returnnull; } } String[] aliasesArray = StringUtils.toStringArray(aliases); // 所有属性解析、校验完成后封装成BeanDefinitionHolder实例并返回 returnnew BeanDefinitionHolder(beanDefinition, beanName, aliasesArray); }
returnnull; }
@Nullable public AbstractBeanDefinition parseBeanDefinitionElement( Element ele, String beanName, @Nullable BeanDefinition containingBean){
protectedvoidprepareBeanFactory(ConfigurableListableBeanFactory beanFactory){ // Tell the internal bean factory to use the context's class loader etc. // 设置类加载器,存在则直接设置(一般是ApplicationClassLoader),不存在则创建一个新的默认加载器设置到容器中 // 不存在会一直往上找,一直找到java根加载器BoostrapClassLoader beanFactory.setBeanClassLoader(getClassLoader()); // 设置EL表达式解析器 beanFactory.setBeanExpressionResolver(new StandardBeanExpressionResolver(beanFactory.getBeanClassLoader())); // 设置属性注册解析器 beanFactory.addPropertyEditorRegistrar(new ResourceEditorRegistrar(this, getEnvironment()));
// 将当前的ApplicationContext对象交给ApplicationContextAwareProcessor类来处理, // 从而在Aware接口实现类中的注入applicationContext // Configure the bean factory with context callbacks. beanFactory.addBeanPostProcessor(new ApplicationContextAwareProcessor(this));
// 注册自动装配使用到的类 // BeanFactory interface not registered as resolvable type in a plain factory. // MessageSource registered (and found for autowiring) as a bean. beanFactory.registerResolvableDependency(BeanFactory.class, beanFactory); beanFactory.registerResolvableDependency(ResourceLoader.class, this); beanFactory.registerResolvableDependency(ApplicationEventPublisher.class, this); beanFactory.registerResolvableDependency(ApplicationContext.class, this);
// 注册容器使用的监听器 // Register early post-processor for detecting inner beans as ApplicationListeners. beanFactory.addBeanPostProcessor(new ApplicationListenerDetector(this));
//如果当前BeanFactory包含loadTimeWeaver Bean,说明存在类加载期织入AspectJ, // 则把当前BeanFactory交给类加载期BeanPostProcessor实现类LoadTimeWeaverAwareProcessor来处理, // 从而实现类加载期织入AspectJ的目的。 // Detect a LoadTimeWeaver and prepare for weaving, if found. if (beanFactory.containsBean(LOAD_TIME_WEAVER_BEAN_NAME)) { beanFactory.addBeanPostProcessor(new LoadTimeWeaverAwareProcessor(beanFactory)); // Set a temporary ClassLoader for type matching. beanFactory.setTempClassLoader(new ContextTypeMatchClassLoader(beanFactory.getBeanClassLoader())); }
// 注册当前容器环境environment组件Bean // Register default environment beans. if (!beanFactory.containsLocalBean(ENVIRONMENT_BEAN_NAME)) { beanFactory.registerSingleton(ENVIRONMENT_BEAN_NAME, getEnvironment()); } // 注册当前电脑系统环境systemProperties组件Bean if (!beanFactory.containsLocalBean(SYSTEM_PROPERTIES_BEAN_NAME)) { beanFactory.registerSingleton(SYSTEM_PROPERTIES_BEAN_NAME, getEnvironment().getSystemProperties()); } // 注册当前电脑系统的环境变量信息systemEnvironment if (!beanFactory.containsLocalBean(SYSTEM_ENVIRONMENT_BEAN_NAME)) { beanFactory.registerSingleton(SYSTEM_ENVIRONMENT_BEAN_NAME, getEnvironment().getSystemEnvironment()); } }
// Detect a LoadTimeWeaver and prepare for weaving, if found in the meantime // (e.g. through an @Bean method registered by ConfigurationClassPostProcessor) if (beanFactory.getTempClassLoader() == null && beanFactory.containsBean(LOAD_TIME_WEAVER_BEAN_NAME)) { beanFactory.addBeanPostProcessor(new LoadTimeWeaverAwareProcessor(beanFactory)); beanFactory.setTempClassLoader(new ContextTypeMatchClassLoader(beanFactory.getBeanClassLoader())); } }
// Do not initialize FactoryBeans here: We need to leave all regular beans // uninitialized to let the bean factory post-processors apply to them! // Separate between BeanDefinitionRegistryPostProcessors that implement // PriorityOrdered, Ordered, and the rest. List<BeanDefinitionRegistryPostProcessor> currentRegistryProcessors = new ArrayList<>();
// Do not initialize FactoryBeans here: We need to leave all regular beans // uninitialized to let the bean factory post-processors apply to them! // 不要再这里初始化FactoryBean,我们需要保留到所有未初始化的普通bean以便bean工厂后置处理可以处理 // 如果开启了注解方式(项目中使用<context:component-scan/>或者<context:annotation-config/>或者@ComponentScan注解), // 这里仍然可以获取到ConfigurationAnnotationProcessor, // 因为它也实现了BeanFactoryPostProcessor接口(postProcessBeanFactory()方法) String[] postProcessorNames = beanFactory.getBeanNamesForType(BeanFactoryPostProcessor.class, true, false);
// Separate between BeanFactoryPostProcessors that implement PriorityOrdered, // Ordered, and the rest. List<BeanFactoryPostProcessor> priorityOrderedPostProcessors = new ArrayList<>(); List<String> orderedPostProcessorNames = new ArrayList<>(); List<String> nonOrderedPostProcessorNames = new ArrayList<>(); // 根据bean后置处理器的接口类型分类 for (String ppName : postProcessorNames) { // 排除前面已经执行过的bean工厂后置处理器(BeanDefinitionRegistryPostProcessor) if (processedBeans.contains(ppName)) { // skip - already processed in first phase above } elseif (beanFactory.isTypeMatch(ppName, PriorityOrdered.class)) { priorityOrderedPostProcessors.add(beanFactory.getBean(ppName, BeanFactoryPostProcessor.class)); } elseif (beanFactory.isTypeMatch(ppName, Ordered.class)) { orderedPostProcessorNames.add(ppName); } else { nonOrderedPostProcessorNames.add(ppName); } }
// First, invoke the BeanFactoryPostProcessors that implement PriorityOrdered. sortPostProcessors(priorityOrderedPostProcessors, beanFactory); // 执行ConfigurationAnnotationProcessor的postProcessBeanFactory()方法 // 用于解析@Configuration注解的类中用@Bean注解的声明的bean,并把声明的bean转换BeanDefinition,注册到容器中 invokeBeanFactoryPostProcessors(priorityOrderedPostProcessors, beanFactory);
// Next, invoke the BeanFactoryPostProcessors that implement Ordered. List<BeanFactoryPostProcessor> orderedPostProcessors = new ArrayList<>(orderedPostProcessorNames.size()); for (String postProcessorName : orderedPostProcessorNames) { orderedPostProcessors.add(beanFactory.getBean(postProcessorName, BeanFactoryPostProcessor.class)); } sortPostProcessors(orderedPostProcessors, beanFactory); invokeBeanFactoryPostProcessors(orderedPostProcessors, beanFactory);
// Finally, invoke all other BeanFactoryPostProcessors. List<BeanFactoryPostProcessor> nonOrderedPostProcessors = new ArrayList<>(nonOrderedPostProcessorNames.size()); for (String postProcessorName : nonOrderedPostProcessorNames) { nonOrderedPostProcessors.add(beanFactory.getBean(postProcessorName, BeanFactoryPostProcessor.class)); } invokeBeanFactoryPostProcessors(nonOrderedPostProcessors, beanFactory);
// Clear cached merged bean definitions since the post-processors might have // modified the original metadata, e.g. replacing placeholders in values... // 清除元数据缓存,因为后置处理器可能已经修改的原始元数据,比如替换值的占位符。。。 beanFactory.clearMetadataCache(); }
/** * 实现BeanDefinitionRegistryPostProcessor接口的postProcessBeanDefinitionRegistry方法。在 * @see org.springframework.context.support.AbstractApplicationContext 的refresh() -> invokeBeanFactoryPostProcessors()方法会调用, * 作用是往容器中注册bean定义,包括使用`@Component`/`@Service`/`@Controller`/`@Import`/`@Bean`等注解定义的类, * 这些类会被转换成BeanDefinition注册到容器中。 * Derive further bean definitions from the configuration classes in the registry. * 从注册表中的配置类派生更多的bean定义。 */ @Override publicvoidpostProcessBeanDefinitionRegistry(BeanDefinitionRegistry registry){ int registryId = System.identityHashCode(registry); if (this.registriesPostProcessed.contains(registryId)) { thrownew IllegalStateException( "postProcessBeanDefinitionRegistry already called on this post-processor against " + registry); } if (this.factoriesPostProcessed.contains(registryId)) { thrownew IllegalStateException( "postProcessBeanFactory already called on this post-processor against " + registry); } this.registriesPostProcessed.add(registryId); // 非常重要的方法,在此方法内解析bean定义 processConfigBeanDefinitions(registry); }
/** * Build and validate a configuration model based on the registry of * {@link Configuration} classes. * 基于配置类的注册表构建并校验配置模型 * * 在这个processConfigBeanDefinitions方法中会做很多事情, * 会解析类上面标注了@ComponentScan、@Import、@bean、@Component等注解信息, * 对于@ComponentScan会解析出需要扫描的包,然后利用ASM技术得到这个类,然后再次解析类上面的注解, * 对于@Import来说,由于支持带入普通类、ImportSelector的实现类和ImportBeanDefinitionRegistrar的实现了, * 所以在解析@Import的时候,会进行判断三种情况, * 然后执行ImportBeanDefinitionRegistrar和ImportSelector接口中的方法,对于导入的类,也会进行判断类中标注的注解(使用递归), */ publicvoidprocessConfigBeanDefinitions(BeanDefinitionRegistry registry){ List<BeanDefinitionHolder> configCandidates = new ArrayList<>(); // 获取容器中所有的bean定义名称 String[] candidateNames = registry.getBeanDefinitionNames();
for (String beanName : candidateNames) { // 通过bean名称拿到对应的bean定义 BeanDefinition beanDef = registry.getBeanDefinition(beanName); // 判断是否被解析过了 // 如果BeanDefinition中configurationClass属性为full或者lite,则说明配置类已经处理过 if (beanDef.getAttribute(ConfigurationClassUtils.CONFIGURATION_CLASS_ATTRIBUTE) != null) { if (logger.isDebugEnabled()) { logger.debug("Bean definition has already been processed as a configuration class: " + beanDef); } } // 判断是否为配置类,比如一个类上面使用@Configuraton注解 elseif (ConfigurationClassUtils.checkConfigurationClassCandidate(beanDef, this.metadataReaderFactory)) { // 添加到候选的配置类集合中 configCandidates.add(new BeanDefinitionHolder(beanDef, beanName)); } }
// Return immediately if no @Configuration classes were found // 在bean列表中没有找到任何一个使用了@Configuration注解的类 if (configCandidates.isEmpty()) { return; }
// Sort by previously determined @Order value, if applicable // 如果容器中扫描到多个使用了@Configuration注解的配置类,则根据@Order排序 /* 比如如下的使用方式:可以返回第一个名为 @Configuration public class JavaConfigA { @Bean(name="bmw") public Car getBMW(){ // 返回实现了Car的名为bmw的单例 return new BMW(); } } */ configCandidates.sort((bd1, bd2) -> { int i1 = ConfigurationClassUtils.getOrder(bd1.getBeanDefinition()); int i2 = ConfigurationClassUtils.getOrder(bd2.getBeanDefinition()); return Integer.compare(i1, i2); });
// Detect any custom bean name generation strategy supplied through the enclosing application context SingletonBeanRegistry sbr = null; if (registry instanceof SingletonBeanRegistry) { sbr = (SingletonBeanRegistry) registry; if (!this.localBeanNameGeneratorSet) { // CONFIGURATION_BEAN_NAME_GENERATOR="org.springframework.context.annotation.internalConfigurationBeanNameGenerator" BeanNameGenerator generator = (BeanNameGenerator) sbr.getSingleton( AnnotationConfigUtils.CONFIGURATION_BEAN_NAME_GENERATOR); if (generator != null) { // 设置@ComponentScan导入的bean的名字生成器 this.componentScanBeanNameGenerator = generator; // 设置@Import导入进来的bean的名字生成器 this.importBeanNameGenerator = generator; } } }
if (this.environment == null) { // 初始化一个标准的环境变量实例,里面会默认初始化喜欢环境变量, // 项目属性:System.getEnv()/System.getProperties() this.environment = new StandardEnvironment(); }
// Parse each @Configuration class // 创建一个@Configuration解析器 ConfigurationClassParser parser = new ConfigurationClassParser( this.metadataReaderFactory, this.problemReporter, this.environment, this.resourceLoader, this.componentScanBeanNameGenerator, registry);
// 用于将之前加入的configCandidate进行去重,Spring内部是没有重复的,但是不能保证用户添加了重复,有可能一个项目定义了多个配置类 Set<BeanDefinitionHolder> candidates = new LinkedHashSet<>(configCandidates); // 存放已经解析出来的配置类,用于判断是否已处理过 Set<ConfigurationClass> alreadyParsed = new HashSet<>(configCandidates.size()); do { // 因为前面已经配置了数组非空,所以肯定有一个配置类才到这里 // 解析配置类,这个方法里面的解析过程也是非常复杂而繁琐的。 // 这个和AbstractApplicationContext.refresh() -> obtainFreshBeanFactory()方法里面的解析xml配置有点类似 parser.parse(candidates); parser.validate();
// 拿到解析出来的配置类 Set<ConfigurationClass> configClasses = new LinkedHashSet<>(parser.getConfigurationClasses()); // 配置类已经解析完毕,从已经解析的列表 configClasses.removeAll(alreadyParsed);
// Read the model and create bean definitions based on its content // 在上下文中读取并创建bean定义 if (this.reader == null) { this.reader = new ConfigurationClassBeanDefinitionReader( registry, this.sourceExtractor, this.resourceLoader, this.environment, this.importBeanNameGenerator, parser.getImportRegistry()); } // 把配置类中配置的bean定义加载注册到容器 this.reader.loadBeanDefinitions(configClasses); alreadyParsed.addAll(configClasses);
candidates.clear(); // candidateNames包括了容器中的所有普通的bean定义(除了@Configuration注册的bean定义) // 再获取一下容器中的所有bean定义,如果有增加说明前面的已经有bean被解析并且注册到容器中 if (registry.getBeanDefinitionCount() > candidateNames.length) { String[] newCandidateNames = registry.getBeanDefinitionNames(); Set<String> oldCandidateNames = new HashSet<>(Arrays.asList(candidateNames)); Set<String> alreadyParsedClasses = new HashSet<>(); for (ConfigurationClass configurationClass : alreadyParsed) { alreadyParsedClasses.add(configurationClass.getMetadata().getClassName()); } for (String candidateName : newCandidateNames) { if (!oldCandidateNames.contains(candidateName)) { BeanDefinition bd = registry.getBeanDefinition(candidateName); if (ConfigurationClassUtils.checkConfigurationClassCandidate(bd, this.metadataReaderFactory) && !alreadyParsedClasses.contains(bd.getBeanClassName())) { candidates.add(new BeanDefinitionHolder(bd, candidateName)); } } } candidateNames = newCandidateNames; } } while (!candidates.isEmpty());
// Register the ImportRegistry as a bean in order to support ImportAware @Configuration classes if (sbr != null && !sbr.containsSingleton(IMPORT_REGISTRY_BEAN_NAME)) { sbr.registerSingleton(IMPORT_REGISTRY_BEAN_NAME, parser.getImportRegistry()); }
if (this.metadataReaderFactory instanceof CachingMetadataReaderFactory) { // Clear cache in externally provided MetadataReaderFactory; this is a no-op // for a shared cache since it'll be cleared by the ApplicationContext. ((CachingMetadataReaderFactory) this.metadataReaderFactory).clearCache(); } }
/** * Apply processing and build a complete {@link ConfigurationClass} by reading the * annotations, members and methods from the source class. This method can be called * multiple times as relevant sources are discovered. * * 1. 一个配置类的成员类(配置类内嵌套定义的类)也可能适配类,先遍历这些成员配置类,调用processConfigurationClass处理它们; * 2. 处理配置类上的注解@PropertySources,@PropertySource * 3. 处理配置类上的注解@ComponentScans,@ComponentScan * 4. 处理配置类上的注解@Import * 5. 处理配置类上的注解@ImportResource * 6. 处理配置类中每个带有@Bean注解的方法 * 7. 处理配置类所实现接口的缺省方法 * 8. 检查父类是否需要处理,如果父类需要处理返回父类,否则返回null * * @param configClass the configuration class being build * @param sourceClass a source class * @return the superclass, or {@code null} if none found or previously processed */ @Nullable protectedfinal SourceClass doProcessConfigurationClass(ConfigurationClass configClass, SourceClass sourceClass) throws IOException {
// 使用了@Configuration注解的类肯定是也是@Component注解的类,因为@Configuration继承了@Component if (configClass.getMetadata().isAnnotated(Component.class.getName())) { // Recursively process any member (nested) classes first // 默认情况下会执行进去,但是方法内判断会不通过,相当于没做任何事情 processMemberClasses(configClass, sourceClass); }
// Process any @PropertySource annotations // 2、处理属性资源文件,使用@PropertySource注解可以导入Properties属性文件 for (AnnotationAttributes propertySource : AnnotationConfigUtils.attributesForRepeatable( sourceClass.getMetadata(), PropertySources.class, org.springframework.context.annotation.PropertySource.class)) { if (this.environment instanceof ConfigurableEnvironment) { processPropertySource(propertySource); } else { logger.info("Ignoring @PropertySource annotation on [" + sourceClass.getMetadata().getClassName() + "]. Reason: Environment must implement ConfigurableEnvironment"); } }
// Process any @ComponentScan annotations // 处理@ComponentScan/@ComponentScans注解,获取注解上的属性值,比如basePackages属性值 Set<AnnotationAttributes> componentScans = AnnotationConfigUtils.attributesForRepeatable( sourceClass.getMetadata(), ComponentScans.class, ComponentScan.class); if (!componentScans.isEmpty() && !this.conditionEvaluator.shouldSkip(sourceClass.getMetadata(), ConfigurationPhase.REGISTER_BEAN)) { // 解析basePackages指定的包和子包下的类并转换成BeanDefinition for (AnnotationAttributes componentScan : componentScans) { // The config class is annotated with @ComponentScan -> perform the scan immediately Set<BeanDefinitionHolder> scannedBeanDefinitions = this.componentScanParser.parse(componentScan, sourceClass.getMetadata().getClassName()); // Check the set of scanned definitions for any further config classes and parse recursively if needed for (BeanDefinitionHolder holder : scannedBeanDefinitions) { BeanDefinition bdCand = holder.getBeanDefinition().getOriginatingBeanDefinition(); if (bdCand == null) { bdCand = holder.getBeanDefinition(); } // 如果扫描的basePackages指定的包和子包下的类还有使用了@Configuration注解则递归解析 if (ConfigurationClassUtils.checkConfigurationClassCandidate(bdCand, this.metadataReaderFactory)) { parse(bdCand.getBeanClassName(), holder.getBeanName()); } } } }
// Process any @Import annotations // 处理@Import注解,@Import(MyImportSelector.class),MyImportSelector必须实现importSelector接口 /* 用法如下: public class MyImportSelector implements ImportSelector { @Override public String[] selectImports(AnnotationMetadata importingClassMetadata) { return new String[] { MyImportSelectorBean.class.getName() }; } } */ // @Import注解要和@Configuration一起用 processImports(configClass, sourceClass, getImports(sourceClass), true);
// 处理@Configuration配置类中使用@Bean注解的方法,比如: /** @Configuration public class AppConfig { @Bean public myServiceImpl() { return new MyServiceImpl(); } } */ // Process individual @Bean methods Set<MethodMetadata> beanMethods = retrieveBeanMethodMetadata(sourceClass); for (MethodMetadata methodMetadata : beanMethods) { configClass.addBeanMethod(new BeanMethod(methodMetadata, configClass)); }
// Process default methods on interfaces processInterfaces(configClass, sourceClass);
// 处理配置类的父类,比如: /** public class AnnotationConfigApplicationContextConfig extends AnnotationConfigApplicationContextConfigParent { } public class AnnotationConfigApplicationContextConfigParent { @Bean public ParentConfigService parentConfigService() { return new ParentConfigService(); } } */ // Process superclass, if any if (sourceClass.getMetadata().hasSuperClass()) { String superclass = sourceClass.getMetadata().getSuperClassName(); // 排除java.xxx开头的包类,因为所有的类终究会继承顶层父类java.lang.Object。 if (superclass != null && !superclass.startsWith("java") && !this.knownSuperclasses.containsKey(superclass)) { this.knownSuperclasses.put(superclass, configClass); // Superclass found, return its annotation metadata and recurse return sourceClass.getSuperClass(); } }
// No superclass -> processing is complete returnnull; }
// Register BeanPostProcessorChecker that logs an info message when // a bean is created during BeanPostProcessor instantiation, i.e. when // a bean is not eligible for getting processed by all BeanPostProcessors. int beanProcessorTargetCount = beanFactory.getBeanPostProcessorCount() + 1 + postProcessorNames.length; beanFactory.addBeanPostProcessor(new BeanPostProcessorChecker(beanFactory, beanProcessorTargetCount));
// 根据BeanPostProcessor的实现不同区分开 // Separate between BeanPostProcessors that implement PriorityOrdered, // Ordered, and the rest. List<BeanPostProcessor> priorityOrderedPostProcessors = new ArrayList<>(); List<BeanPostProcessor> internalPostProcessors = new ArrayList<>(); List<String> orderedPostProcessorNames = new ArrayList<>(); List<String> nonOrderedPostProcessorNames = new ArrayList<>(); for (String ppName : postProcessorNames) { if (beanFactory.isTypeMatch(ppName, PriorityOrdered.class)) { BeanPostProcessor pp = beanFactory.getBean(ppName, BeanPostProcessor.class); priorityOrderedPostProcessors.add(pp); // 同时实现了PriorityOrdered接口和MergedBeanPostProcessor接口的实现类 if (pp instanceof MergedBeanDefinitionPostProcessor) { internalPostProcessors.add(pp); } } elseif (beanFactory.isTypeMatch(ppName, Ordered.class)) { orderedPostProcessorNames.add(ppName); } else { nonOrderedPostProcessorNames.add(ppName); } }
// First, register the BeanPostProcessors that implement PriorityOrdered. sortPostProcessors(priorityOrderedPostProcessors, beanFactory); registerBeanPostProcessors(beanFactory, priorityOrderedPostProcessors);
// Next, register the BeanPostProcessors that implement Ordered. List<BeanPostProcessor> orderedPostProcessors = new ArrayList<>(orderedPostProcessorNames.size()); for (String ppName : orderedPostProcessorNames) { BeanPostProcessor pp = beanFactory.getBean(ppName, BeanPostProcessor.class); orderedPostProcessors.add(pp); // 同时实现了Ordered接口和MergeBeanPostProcessor接口的 if (pp instanceof MergedBeanDefinitionPostProcessor) { internalPostProcessors.add(pp); } } sortPostProcessors(orderedPostProcessors, beanFactory); // 每次注册到容器时都是先删除再添加,所以不会重复 registerBeanPostProcessors(beanFactory, orderedPostProcessors);
// Now, register all regular BeanPostProcessors. List<BeanPostProcessor> nonOrderedPostProcessors = new ArrayList<>(nonOrderedPostProcessorNames.size()); for (String ppName : nonOrderedPostProcessorNames) { BeanPostProcessor pp = beanFactory.getBean(ppName, BeanPostProcessor.class); nonOrderedPostProcessors.add(pp); // 没有实现PriorityOrdered接口,没有实现Ordered接口,但是仅实现了MergedBeanPosProcessor接口的 if (pp instanceof MergedBeanDefinitionPostProcessor) { internalPostProcessors.add(pp); } } // 每次注册到容器时都是先删除再添加,所以不会重复 registerBeanPostProcessors(beanFactory, nonOrderedPostProcessors);
// Re-register post-processor for detecting inner beans as ApplicationListeners, // moving it to the end of the processor chain (for picking up proxies etc). // 重新注册,目的就是把此BeanPostProcessor放在数组末尾 beanFactory.addBeanPostProcessor(new ApplicationListenerDetector(applicationContext)); }
// Do not initialize FactoryBeans here: We need to leave all regular beans // uninitialized to let post-processors apply to them! // 注册用户定义的监听器,比如com.ubuntuvim.spring.event.MyListener就是在这里注册的。 String[] listenerBeanNames = getBeanNamesForType(ApplicationListener.class, true, false); for (String listenerBeanName : listenerBeanNames) { // getApplicationEventMulticaster()拿到的就是refresh()方法中initApplicationEventMulticaster()定义的发布器 getApplicationEventMulticaster().addApplicationListenerBean(listenerBeanName); }
// Publish early application events now that we finally have a multicaster... Set<ApplicationEvent> earlyEventsToProcess = this.earlyApplicationEvents; this.earlyApplicationEvents = null; if (earlyEventsToProcess != null) { for (ApplicationEvent earlyEvent : earlyEventsToProcess) { getApplicationEventMulticaster().multicastEvent(earlyEvent); } } }
protectedvoidfinishBeanFactoryInitialization(ConfigurableListableBeanFactory beanFactory){ // Initialize conversion service for this context. // 初始化上下文的转换服务 if (beanFactory.containsBean(CONVERSION_SERVICE_BEAN_NAME) && beanFactory.isTypeMatch(CONVERSION_SERVICE_BEAN_NAME, ConversionService.class)) { beanFactory.setConversionService( beanFactory.getBean(CONVERSION_SERVICE_BEAN_NAME, ConversionService.class)); }
// Register a default embedded value resolver if no bean post-processor // (such as a PropertyPlaceholderConfigurer bean) registered any before: // at this point, primarily for resolution in annotation attribute values. // 如果前面没有注册配置解析器,则注入配置解析器,主要用来处理配置文件的占位符等 if (!beanFactory.hasEmbeddedValueResolver()) { beanFactory.addEmbeddedValueResolver(strVal -> getEnvironment().resolvePlaceholders(strVal)); }
// Initialize LoadTimeWeaverAware beans early to allow for registering their transformers early. String[] weaverAwareNames = beanFactory.getBeanNamesForType(LoadTimeWeaverAware.class, false, false); for (String weaverAwareName : weaverAwareNames) { getBean(weaverAwareName); }
// Stop using the temporary ClassLoader for type matching. // 停止使用临时ClassLoader进行类型匹配 beanFactory.setTempClassLoader(null);
// Allow for caching all bean definition metadata, not expecting further changes. // 冻结所有的Bean定义,在此后bean定义不会再被更改,因为在后面的方法就要开始根据bean定义创建bean实例了。 // 所有的bean定义在此后修改将是无任何效果的 beanFactory.freezeConfiguration();
/** * 实例化所有除了Spring内部的单例(懒加载的、抽象类、非单例的除外) */ @Override publicvoidpreInstantiateSingletons()throws BeansException { if (logger.isTraceEnabled()) { logger.trace("Pre-instantiating singletons in " + this); }
// Iterate over a copy to allow for init methods which in turn register new bean definitions. // While this may not be part of the regular factory bootstrap, it does otherwise work fine. // 创建BeanDefinitionName副本,用于后续遍历,以允许init等方法注册新的bean定义 List<String> beanNames = new ArrayList<>(this.beanDefinitionNames);
/** * Return an instance, which may be shared or independent, of the specified bean. * 返回指定beanName的实例 * IoC容器初始化bean时通过调用的是getBean(String name)方法,所以,方法后面的三个参数是:null,null,false */ @SuppressWarnings("unchecked") protected <T> T doGetBean(final String name, @Nullablefinal Class<T> requiredType, @Nullablefinal Object[] args, boolean typeCheckOnly)throws BeansException {
final String beanName = transformedBeanName(name); Object bean;
// Eagerly check singleton cache for manually registered singletons. // 先获取早期的单例对象,先查缓存,如果这个bean已经创建过则直接返回(有可能还没做初始化属性赋值,是个半成品的实例,但是它的地址不会变了可以提前返回) Object sharedInstance = getSingleton(beanName); if (sharedInstance != null && args == null) { if (logger.isTraceEnabled()) { if (isSingletonCurrentlyInCreation(beanName)) { logger.trace("Returning eagerly cached instance of singleton bean '" + beanName + "' that is not fully initialized yet - a consequence of a circular reference"); } else { logger.trace("Returning cached instance of singleton bean '" + beanName + "'"); } } // 获取bean实例对象,如果是工厂bean则设置bean的属性isFactoryBean为true bean = getObjectForBeanInstance(sharedInstance, name, beanName, null); } // 缓存中还没有beanName对应的实例 else { // Fail if we're already creating this bean instance: // We're assumably within a circular reference. // 如果是原型类型的bean直接抛异常 if (isPrototypeCurrentlyInCreation(beanName)) { thrownew BeanCurrentlyInCreationException(beanName); }
// Check if bean definition exists in this factory. // 检查是否存在父工厂,一般情况下开发者不会自定义工厂的实现,所以这里是一个null BeanFactory parentBeanFactory = getParentBeanFactory(); if (parentBeanFactory != null && !containsBeanDefinition(beanName)) { // Not found -> check parent. String nameToLookup = originalBeanName(name); if (parentBeanFactory instanceof AbstractBeanFactory) { return ((AbstractBeanFactory) parentBeanFactory).doGetBean( nameToLookup, requiredType, args, typeCheckOnly); } elseif (args != null) { // 容器初始化调用getBean(String name)方法时args为null // Delegation to parent with explicit args. return (T) parentBeanFactory.getBean(nameToLookup, args); } elseif (requiredType != null) { // 容器初始化调用getBean(String name)方法时requiredType为null // No args -> delegate to standard getBean method. return parentBeanFactory.getBean(nameToLookup, requiredType); } else { return (T) parentBeanFactory.getBean(nameToLookup); } }
if (!typeCheckOnly) { // 把创建好的bean实例标记成创建成功(就是把创建好的bean放到已经创建完成的数组里面) markBeanAsCreated(beanName); }
/** * Central method of this class: creates a bean instance, * populates the bean instance, applies post-processors, etc. * 本类的核心方法:创建bean实例,填充bean实例属性,应用(执行)后置处理, * 详细处理逻辑在doCreateBean方法实现 * @see #doCreateBean */ @Override protected Object createBean(String beanName, RootBeanDefinition mbd, @Nullable Object[] args) throws BeanCreationException {
if (logger.isTraceEnabled()) { logger.trace("Creating instance of bean '" + beanName + "'"); } RootBeanDefinition mbdToUse = mbd;
// Make sure bean class is actually resolved at this point, and // clone the bean definition in case of a dynamically resolved Class // which cannot be stored in the shared merged bean definition. // 通过Class.forName(bean)方法获取实例,合并bean定义 Class<?> resolvedClass = resolveBeanClass(mbd, beanName); if (resolvedClass != null && !mbd.hasBeanClass() && mbd.getBeanClassName() != null) { mbdToUse = new RootBeanDefinition(mbd); mbdToUse.setBeanClass(resolvedClass); }
if (logger.isTraceEnabled()) { logger.trace("Creating instance of bean '" + beanName + "'"); } RootBeanDefinition mbdToUse = mbd;
// Make sure bean class is actually resolved at this point, and // clone the bean definition in case of a dynamically resolved Class // which cannot be stored in the shared merged bean definition. // 通过Class.forName(bean)方法获取实例,合并bean定义 Class<?> resolvedClass = resolveBeanClass(mbd, beanName); if (resolvedClass != null && !mbd.hasBeanClass() && mbd.getBeanClassName() != null) { mbdToUse = new RootBeanDefinition(mbd); mbdToUse.setBeanClass(resolvedClass); }
// Eagerly cache singletons to be able to resolve circular references // even when triggered by lifecycle interfaces like BeanFactoryAware. // 单例bean && 允许循环依赖 && bean正在被创建 boolean earlySingletonExposure = (mbd.isSingleton() && this.allowCircularReferences && isSingletonCurrentlyInCreation(beanName)); if (earlySingletonExposure) { if (logger.isTraceEnabled()) { logger.trace("Eagerly caching bean '" + beanName + "' to allow for resolving potential circular references"); } /** * 执行后置处理器SmartInstantiationAwareBeanPostProcessor的getEarlyBeanReference()方法尝试获取一个早期的引用。 * 并加入的单例工厂缓存中 * @see DefaultSingletonBeanRegistry#addSingletonFactory(String, ObjectFactory) * @see #getEarlyBeanReference */ addSingletonFactory(beanName, () -> getEarlyBeanReference(beanName, mbd, bean)); }
// Initialize the bean instance. // 初始化bean实例,填充属性,注入依赖(@Autowired,@Resource,@Value)注解的属性 Object exposedObject = bean; try { populateBean(beanName, mbd, instanceWrapper); /** 执行bean的初始化回调方法以及执行后置处理器的初始化方法,包括: 一,执行Aware接口 ,包括BeanFactoryAware,BeanClassLoaderAware,BeanNameAware 注意:ApplicationContext的注入是在另外一个后置处理器ApplicationContextAwareProcessor中执行。 二,执行bean初始化回调,包括: 0. 执行初始化回调BeanPostProcessor.postProcessBeforeInitialization()方法 1. 执行初始化回调@PostConstruct注解定义的方法 2. 执行初始化回调InitializingBean.afterPropertiesSet()方法 3. 执行初始化回调@Bean(initMethod = "beanInit")定义的初始化方法beanInit() 4. 执行初始化回调BeanPostProcessor.postProcessAfterInitialization()方法 5. 执行初始化回调SmartInitializingSingleton.afterSingletonsInstantiated()方法 按照上述执行顺序执行 */ exposedObject = initializeBean(beanName, exposedObject, mbd); } catch (Throwable ex) { if (ex instanceof BeanCreationException && beanName.equals(((BeanCreationException) ex).getBeanName())) { throw (BeanCreationException) ex; } else { thrownew BeanCreationException( mbd.getResourceDescription(), beanName, "Initialization of bean failed", ex); } } // 循环依赖检查 if (earlySingletonExposure) { Object earlySingletonReference = getSingleton(beanName, false); if (earlySingletonReference != null) { if (exposedObject == bean) { exposedObject = earlySingletonReference; } elseif (!this.allowRawInjectionDespiteWrapping && hasDependentBean(beanName)) { String[] dependentBeans = getDependentBeans(beanName); Set<String> actualDependentBeans = new LinkedHashSet<>(dependentBeans.length); for (String dependentBean : dependentBeans) { if (!removeSingletonIfCreatedForTypeCheckOnly(dependentBean)) { actualDependentBeans.add(dependentBean); } } if (!actualDependentBeans.isEmpty()) { thrownew BeanCurrentlyInCreationException(beanName, "Bean with name '" + beanName + "' has been injected into other beans [" + StringUtils.collectionToCommaDelimitedString(actualDependentBeans) + "] in its raw version as part of a circular reference, but has eventually been " + "wrapped. This means that said other beans do not use the final version of the " + "bean. This is often the result of over-eager type matching - consider using " + "'getBeanNamesOfType' with the 'allowEagerInit' flag turned off, for example."); } } } }
protected BeanWrapper createBeanInstance(String beanName, RootBeanDefinition mbd, @Nullable Object[] args){ // Make sure bean class is actually resolved at this point. Class<?> beanClass = resolveBeanClass(mbd, beanName);
// 检查bean的访问类型,比如是public并且是非final if (beanClass != null && !Modifier.isPublic(beanClass.getModifiers()) && !mbd.isNonPublicAccessAllowed()) { thrownew BeanCreationException(mbd.getResourceDescription(), beanName, "Bean class isn't public, and non-public access not allowed: " + beanClass.getName()); } // 存在Supplier回调则使用回调里的方法创建实例(jdk1.8)之后的才有的特性 // 通过instanceSupplier.get()方法返回实例 Supplier<?> instanceSupplier = mbd.getInstanceSupplier(); if (instanceSupplier != null) { return obtainFromSupplier(instanceSupplier, beanName); } // 通过工厂方法创建实例 if (mbd.getFactoryMethodName() != null) { return instantiateUsingFactoryMethod(beanName, mbd, args); }
protectedvoidpopulateBean(String beanName, RootBeanDefinition mbd, @Nullable BeanWrapper bw){ // 前面创建的bean实例为空时 if (bw == null) { if (mbd.hasPropertyValues()) { thrownew BeanCreationException( mbd.getResourceDescription(), beanName, "Cannot apply property values to null instance"); } else { // Skip property population phase for null instance. // 当前bean实例都是null也就无法填充属性值了,直接返回 return; } }
// Give any InstantiationAwareBeanPostProcessors the opportunity to modify the // state of the bean before properties are set. This can be used, for example, // to support styles of field injection. // 执行后置处理器InstantiationAwareBeanPostProcessor,提供一个机会让开发者可以在bean实例化后,初始化前做一些操作。 if (!mbd.isSynthetic() && hasInstantiationAwareBeanPostProcessors()) { for (BeanPostProcessor bp : getBeanPostProcessors()) { if (bp instanceof InstantiationAwareBeanPostProcessor) { InstantiationAwareBeanPostProcessor ibp = (InstantiationAwareBeanPostProcessor) bp; // 如果返回false则直接退出当前方法,不进行下面的属性填充操作,所以一定要非常注意后置处理器的返回值以及执行顺序。 if (!ibp.postProcessAfterInstantiation(bw.getWrappedInstance(), beanName)) { return; } } } } // 获取属性值 PropertyValues pvs = (mbd.hasPropertyValues() ? mbd.getPropertyValues() : null); // 获取注入模式(byType或者byName) int resolvedAutowireMode = mbd.getResolvedAutowireMode(); if (resolvedAutowireMode == AUTOWIRE_BY_NAME || resolvedAutowireMode == AUTOWIRE_BY_TYPE) { // 把属性值再做一次包装,转换成一个MutablePropertyValues对象。 MutablePropertyValues newPvs = new MutablePropertyValues(pvs); // Add property values based on autowire by name if applicable. // 如果适用,根据类型添加基于自动装配的属性值。 if (resolvedAutowireMode == AUTOWIRE_BY_NAME) { autowireByName(beanName, mbd, bw, newPvs); } // Add property values based on autowire by type if applicable. // 如果适用,根据类型添加基于自动装配的属性值。 if (resolvedAutowireMode == AUTOWIRE_BY_TYPE) { autowireByType(beanName, mbd, bw, newPvs); } pvs = newPvs; } // 存在InstantiationAwareBeanPostProcessor后置处理器 boolean hasInstAwareBpps = hasInstantiationAwareBeanPostProcessors();
// Don't let calling code try to dereference the factory if the bean isn't a factory. // 如果不是FactoryBean,为了以防开发者自定义的bean名字也加了&前缀,因为Spring默认&开头的bean是工厂bean if (BeanFactoryUtils.isFactoryDereference(name)) { if (beanInstance instanceof NullBean) { return beanInstance; } if (!(beanInstance instanceof FactoryBean)) { thrownew BeanIsNotAFactoryException(beanName, beanInstance.getClass()); } if (mbd != null) { mbd.isFactoryBean = true; } return beanInstance; }
// Now we have the bean instance, which may be a normal bean or a FactoryBean. // If it's a FactoryBean, we use it to create a bean instance, unless the // caller actually wants a reference to the factory. // 如果不是FactoryBean则无需通过调用getObject方法获取实例, // 正常情况下普通的bean已经在前面的doCreateBean方法中创建好了 if (!(beanInstance instanceof FactoryBean)) { return beanInstance; }
Object object = null; if (mbd != null) { mbd.isFactoryBean = true; } else { // 从FactoryBean对象缓存中获取 object = getCachedObjectForFactoryBean(beanName); } if (object == null) { // Return bean instance from factory. // 获取工厂bean实例本身 FactoryBean<?> factory = (FactoryBean<?>) beanInstance; // Caches object obtained from FactoryBean if it is a singleton. if (mbd == null && containsBeanDefinition(beanName)) { mbd = getMergedLocalBeanDefinition(beanName); } boolean synthetic = (mbd != null && mbd.isSynthetic()); // 调用工厂bean的getObject方法获取对象实例 object = getObjectFromFactoryBean(factory, beanName, !synthetic); } return object; }
// Do not accept a null value for a FactoryBean that's not fully // initialized yet: Many FactoryBeans just return null then. // 不接受null对象,如果开发者实现了FactoryBean接口,但是在getObject方法中返回了null,那么Spring会默认返回的一个NullBean对象实例 if (object == null) { if (isSingletonCurrentlyInCreation(beanName)) { thrownew BeanCurrentlyInCreationException( beanName, "FactoryBean which is currently in creation returned null from getObject"); } object = new NullBean(); } return object; }